package com.buybuyyi.stylistcrm.resource.service;

import com.buybuyyi.stylistcrm.resource.dao.ResourceDao;
import com.buybuyyi.stylistcrm.resource.mapper.ObjectResourceMapper;
import com.buybuyyi.stylistcrm.resource.po.ObjectResource;
import com.buybuyyi.stylistcrm.resource.vo.QcloudCosContext;
import com.qcloud.cos.COS;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.http.ResponseBodyKey;
import com.qcloud.cos.request.DelFileRequest;
import com.qcloud.cos.request.UploadFileStreamRequest;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.expression.spel.ast.Literal;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import stylistcrm.core.services.resource.ObjectResourceService;
import stylistcrm.core.services.resource.exception.DeleteFileException;
import stylistcrm.core.services.resource.exception.UploadFileException;

import java.io.*;
import java.util.Date;
import java.util.List;

/**
 * Created by yanwc on 2016/8/23.
 */
@Service
public class ObjectResourceServiceImpl implements ObjectResourceService {
    @Autowired
    public ResourceDao resourceDao;

    @Autowired(required = true)
    private QcloudCosContext qCloudCosContext;

    private static String delInfo_cosPath = "cosPath";
    private static String delInfo_bucketName="bucketName";
    private static String default_bizattr="stylistcrm";

    @Transactional
    public String preSave(InputStream stream, String fileName, String objectName, String tempId, String creator, long creatorId) throws IOException, Exception {
        ObjectResource or = new ObjectResource();
        or.setObjectId(null);
        or.setObjectName(objectName);
        or.setTempId(tempId);
        or.setResourceName(fileName);
        or.setCreateTime(new Date());
        or.setCreator(creator);
        or.setCreatorId(creatorId);
        COS cos = new COSClient(this.qCloudCosContext.getAppid(),
                this.qCloudCosContext.getSecretID(),
                this.qCloudCosContext.getSecretKey());
        String cosPath = this.qCloudCosContext.getCosPath()+fileName;
        UploadFileStreamRequest request =
                new UploadFileStreamRequest(this.qCloudCosContext.getBucketName(),
                        cosPath, stream,fileName);
        request.setBizAttr(default_bizattr);

        String result = cos.uploadFile(request,fileName);
        JSONObject uploadFileJson = new JSONObject(result);
        if (uploadFileJson.getInt(ResponseBodyKey.CODE) != 0) {
            throw new UploadFileException(uploadFileJson.getString(ResponseBodyKey.MESSAGE));
        }
        String access_url = uploadFileJson.getJSONObject("data").getString("access_url");
        or.setResourceAccessUrl(access_url);
        //保存删除地址
        JSONObject delObject = new JSONObject();
        delObject.put(delInfo_bucketName,this.qCloudCosContext.getBucketName());
        delObject.put(delInfo_cosPath,cosPath);
        or.setResourceDeleteinfo(delObject.toString());
        //调用地址访问接口
        this.resourceDao.insert(or);
        return access_url;
    }

    public String preSave(String sourceFileFullName, String fileName, String objectName, String tempId, String creator, long creatorId) throws Exception {
        File f = new File(sourceFileFullName);
        FileInputStream inputStream = new FileInputStream(f);
        return preSave(inputStream,fileName,objectName,tempId,creator,creatorId);
    }

    public void save(String tempId, long objectId) throws ClassNotFoundException {
        ObjectResource objResource = resourceDao.selectByTempId(tempId);
        if(objResource != null){
            objResource.setObjectId(objectId);
            resourceDao.updateByPrimaryKeySelective(objResource);
        }else{
            throw new ClassNotFoundException("临时编号"+tempId+"未找到");
        }
    }

    @Transactional
    public boolean removeImage(long objectId, String objectName) throws DeleteFileException {
        boolean rev = false;
        List<ObjectResource> list = resourceDao.selectByObjectIdAndObjectName(objectId,objectName);
        //查找对象对应的图片信息
        COS cos = new COSClient(this.qCloudCosContext.getAppid(),
                this.qCloudCosContext.getSecretID(),
                this.qCloudCosContext.getSecretKey());
        for(ObjectResource or :list){
            if(or.getResourceDeleteinfo()==null)continue;
            JSONObject delJsonObject =new  JSONObject(or.getResourceDeleteinfo());
            String bucketName = delJsonObject.getString(delInfo_bucketName);
            String cosPath = delJsonObject.getString(delInfo_cosPath);
            DelFileRequest delRequest = new DelFileRequest(bucketName,cosPath);
            String result = cos.delFile(delRequest);
            JSONObject jsonResult = new JSONObject(result);
            int code = jsonResult.getInt(ResponseBodyKey.CODE);
            if(code !=0){
                throw new DeleteFileException("删除文件"+or.getObjectName()+"["+or.getObjectId()+"]异常:["+jsonResult.getString(ResponseBodyKey.MESSAGE)+"]");
            }
            //删除文件
            this.resourceDao.deleteByPrimaryKey(or.getId());
            rev = true;
        }
        return rev;
    }

}
